function update_attr_with_one(old_attr, old_index, new_index) {
    var search = '-' + old_index + '-';
    var new_val = '-' + new_index + '-';
    // console.log('old: ' + search);
    // console.log('new: ' + new_val);
    return old_attr.replace(search, new_val);
}

function update_related_forms_index(formset, class_name, removed_index) {
    // console.log('removed_index = ' + removed_index);
    formset.find('.added').each(function() {
        // console.log($(this).data('index'));
        if ($(this).is(':visible') && $(this).data('index') > removed_index) {
            var old_index = $(this).data('index');
            var new_index = old_index - 1;
            $(this).find("*").each(function(){
                var ele = $(this);
                $.each([ 'name', 'id', 'for' ], function( index, attr_name ) {
                    var attr = ele.attr(attr_name);
                    if (typeof attr !== typeof undefined && attr !== false) {
                        new_attr = update_attr_with_one(attr, old_index, new_index);
                        ele.attr(attr_name, new_attr);
                    }
                });
            });
        }
    });
}

function remove_btn_clicked() {
    // console.log('clicked');
    var class_name = $(this).parent().data('target-form');
    var removed_index = $(this).parent().data('index');
    var formset = $(this).parent().parent();
    $(this).parent().remove();
    var input_total_forms = get_total_form(class_name);
    var new_val = input_total_forms.val() - 1;
    input_total_forms.val(new_val);
    update_related_forms_index(formset, class_name, removed_index);
}

function create_another_form(class_name) {
    var new_form = $('#' + class_name + '-last').clone().show();
    new_form.removeAttr('id');
    var remove_btn = $('<span class="glyphicon glyphicon-remove remove"></span>');
    remove_btn.on('click', remove_btn_clicked);
    new_form.append(remove_btn);
    return new_form;
}

function get_total_form(class_name) {
    var form_mgmt = $('#' + class_name + '-mgmt');
    var input_total_forms;
    form_mgmt.find("input[type='hidden']").each(function(){
        if ($(this).attr('name').indexOf('TOTAL_FORMS') !== -1) {
            input_total_forms = $(this);
            return true;
        }
    });
    return input_total_forms;
}

$(function(){

    $('.btn-add-another').each(function(){

        // hide first init
        var class_name = $(this).attr('target-form');
        var form_mgmt = $('#' + class_name + '-mgmt');

        var input_total_forms = get_total_form(class_name);
        var new_val = input_total_forms.val() - 1;
        input_total_forms.val(new_val);

        $('#' + class_name + '-last').hide();
        $('#' + class_name + '-last').data('index', new_val);

        // bind click event
        $(this).click(function(e) {
            // // console.log($(this));
            var class_name = $(this).attr('target-form');
            // console.log(class_name);

            var form_mgmt = $('#' + class_name + '-mgmt');
            // console.log(form_mgmt);
            var input_total_forms;
            form_mgmt.find("input[type='hidden']").each(function(){
                if ($(this).attr('name').indexOf('TOTAL_FORMS') !== -1) {
                    input_total_forms = $(this);
                    return true;
                }
            });
            // console.log(input_total_forms);
            input_total_forms.val(function(i, oldVal){
                // console.log(oldVal);
                return ++oldVal;
            });

            var new_form_index = input_total_forms.val() - 1;
            // console.log(new_form_index);
            var new_form = create_another_form(class_name);
            new_form.data('index', new_form_index);
            new_form.find("*").each(function(){
                var ele = $(this);
                $.each([ 'name', 'id', 'for' ], function( index, attr_name ) {
                    var attr = ele.attr(attr_name);
                    if (typeof attr !== typeof undefined && attr !== false) {
                        var old_index = $('#' + class_name + '-last').data('index');
                        new_attr = update_attr_with_one(attr, old_index, new_form_index);
                        ele.attr(attr_name, new_attr);
                    }
                });
            });

            new_form.find("input[type='checkbox']").each(function(){
                var ele = $(this)
                if (ele.attr('id').indexOf('-DELETE') !== -1) {
                    var delete_form = ele.parentsUntil('div.form-group').last().parent();
                    delete_form.remove();
                }
            });

            new_form.find('textarea').val('');
            new_form.find('input').each(function() {
                if ($(this).attr('name') == 'csrfmiddlewaretoken') {
                    // console.log('skip csrfmiddlewaretoken');
                } else {
                    $(this).val('');
                }
            });

            $(this).parent().parent().before(new_form);

            if (typeof another_added !== 'undefined') {
                another_added(new_form);
            }

        }); // click
    }); // each btn-add-another

}); // document ready